package com.gl.order.controller;

import com.gl.order.commom.ResultBean;
import com.gl.order.entity.TPermission;
import com.gl.order.entity.dto.PermissionDto;
import com.gl.order.entity.dto.UpdatePermissionDto;
import com.gl.order.service.PermissionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Objects;

/**
 * @Author: liangSY
 * @Date: 2021/6/22 16:03
 * @ClassName: PermissionController
 */
@Api(tags = "权限管理")
@RestController
@RequestMapping("/permissions")
public class PermissionController {

    PermissionService permissionService;

    public PermissionController(PermissionService permissionService) {
        this.permissionService = permissionService;
    }

    @GetMapping("/")
    @ApiOperation("获取所以权限列表")
    public ResultBean<List<TPermission>> list() {
        List<TPermission> list = permissionService.list();
        return ResultBean.success(list);
    }

    @GetMapping("/{id}")
    @ApiOperation("根据权限id获取权限信息")
    @ApiImplicitParam(name = "id", value = "权限id", dataType = "String", paramType = "path")
    public ResultBean<TPermission> findById(@PathVariable("id") String id) {
        TPermission per = permissionService.findById(id);
        return ResultBean.success(per);
    }

    @PostMapping("/")
    @ApiOperation("新增权限")
    public ResultBean addPermission(@RequestBody @Valid PermissionDto dto) {
        TPermission permission = permissionService.findByNameOrCode(dto.getName(), dto.getPermissionCode());
        if (!Objects.isNull(permission)) {
            return ResultBean.success("该权限已存在");
        }
        permissionService.add(dto);
        return ResultBean.success();
    }

    @PutMapping("/")
    @ApiOperation("修改权限")
    public ResultBean updatePermission(@RequestBody @Valid UpdatePermissionDto dto) {
        permissionService.updatePermission(dto);
        return ResultBean.success();
    }

    @DeleteMapping("/{id}")
    @ApiOperation("删除权限")
    @ApiImplicitParam(name = "id", value = "权限id", dataType = "String", paramType = "path")
    public ResultBean delPermission(@PathVariable("id") String id) {
        int n = permissionService.delPermission(id);
        if (n > 0) {
            return ResultBean.success();
        }
        return ResultBean.failed("删除权限失败");
    }


}
